<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");

class TextModel extends Model {
    //表字段配置
    protected $fields   = array(
                                'text_id',
                                'text_name',
                                'text_type',
                                'sort_loc',
                                'text_desc',
                                'image_path',
                                'edit_time',
                                '_pk' => 'text_id',
                                '_autoinc' => true
                            );
    
    //自动验证
    protected $_validate    = array(
        array('text_name', 'require', '标题不能为空！'),
        array('text_type', 'require', '类型不能为空！'),
        array('sort_loc', 'number', '排序编号必须是数字！',2)
    );

    //自动完成
    protected $_auto        = array(
        array('edit_time', 'mktime', 3, 'function')
    );

    protected static $orderFields = 'sort_loc';

    protected static $xmlFields   = 'image_path, text_name, text_desc';

    protected $_imageTypes;
    protected $_imageSize;
    protected $_uploadDir;

    protected $_countWhere;

    protected $_error;

    protected $_modelTypeId;

    //默认详细信息里显示的图片类型
    protected static $infoImgType     = '_s';
    //格式:width, height, type, interlace, 后缀
    protected static $thumbImgInfo  = array(
        '_s' => array('w' => 100, 'h' => 100, 't' => 'jpg', 'i' => true)
    );

    //XML配置参数
    protected static $xmlFilePath   = 'xml/text_type_%d_%d.xml';

    protected static $rootNode      = '<main>%s</main>';
    protected static $childNode     = '<picture>%s</picture><text><![CDATA[%s：<br/>%s]]></text>';

    protected static $subXmlFilePath   = 'xml/subtext_type_%d.xml';
    
    protected static $subRootNode      = '
<menu>
    %s
</menu>';
    protected static $subChildNode     = '
<link type="text">
    <name><![CDATA[<b>%s</b>]]></name>
    <asset>%s</asset>
</link>';
        
    private $_xmlFilePath;
    private $_subXmlContent;
    private $_totalRecord;

    public function __construct() {
        parent::__construct();

        $this->_countWhere      = '';
        $this->_modelTypeId     = '';
        $this->_xmlFilePath     = '';
        $this->_subXmlContent   = '';
        $this->_totalRecord     = 0;
        $this->_imageSize       = 2;
        $this->_imageTypes      = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
        $this->_uploadDir       = 'Public/default/uploadfiles/text';
        $this->_error           = new Error(); 
    }

    //得到记录总数
    public function getCountRecords() {
        return $this->where($this->_countWhere)->count();
    }
    
    //搜索方法
    public function searchText($page = 0, $keyword, $perPage = 10) {
        if(preg_match('/^\/+\d+$/', $keyword)) {
            $whereSearch  = '`text_id` = ' . strtr($keyword, array('/' => ''));
        } else {
            $whereSearch  = '`text_name` like \'%' . $keyword . '%\'';
        }
        $this->_countWhere  = $whereSearch;

        return $this->seeText($page, $whereSearch, $perPage);
    }

    //查看列表方法 
    public function seeText($page = 0, $whereText = '', $perPage = 10) {
        if(empty($whereText)) {
            $whereText          = $this->genWhereModelType();
            $this->_countWhere  = $whereText;
        }
        return $this->where($whereText)->order('sort_loc')->limit($perPage)->page($page)->select();
    }

    //生成模块类型的条件查询片段
    protected function genWhereModelType() {
        if(isset($_GET['type']) && !empty($_GET['type'])) {
            $this->_modelTypeId     = $_GET['type'];
            return '`text_type` = ' . $_GET['type'];
        }
        
        return '';
    }

    //查看记录详细信息方法
    public function infoText($recordId) {
        $record     = $this->where('`text_id` = ' . $recordId)->find();
        if(!empty($record['image_path'])) {
            $record['image_path_small']     = $this->genThumbImageName($record['image_path']) . self::$infoImgType . '.' . self::$thumbImgInfo[self::$infoImgType]['t']; 
        }
        $this->_modelTypeId     = $record['text_type'];

        return $record;
    }

    //编辑记录方法
    public function editText($recordId) {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(isset($_POST['del_image'])) {
            if(!empty($_POST['del_image'])) {
                if(false === $this->deleteFile($_POST['old_image_path'])) {
                    Logger::log('删除文件失败！' . $_POST['old_image_path']);
                }
            } else {
                $_POST['image_path']    = $_POST['old_image_path'];
            }
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->save()) {
            return $this->getError();
        }

        return true;
    }

    //添加记录方法
    public function addText() {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->add()) {
            return false;
            return $this->getError();
        }

        return true;
    }

    //删除记录方法
    public function deleteText($recordId) {

        return $this->quickDeleteText(array($recordId));
    }

    //快捷操作：删除记录
    public function quickDeleteText(array $recordIds){
        $this->quickDeleteImageText($recordIds);
        $whereStr   = $this->genWhereIn('text_id', $recordIds);

        return $this->where($whereStr)->delete();
    }

    //快捷操作：删除记录相关文件
    public function quickDeleteImageText(array $recordIds) {
        $whereStr   = $this->genWhereIn('text_id', $recordIds) . ' AND (`image_path` !=\'\' AND `image_path` IS NOT NULL)';
        $recordList = $this->where($whereStr)->field('text_id, image_path')->select();
        if(empty($recordList)) {
            return ture;
        }
        $whereStr   = '`text_id` IN (';
        foreach($recordList as $record) {
            if($this->deleteFile($record['image_path'])) {
                $whereStr   .= $record['text_id'] . ', ';
            }
        }
        $whereStr    .= '-1)'; 

        return $this->where($whereStr)->setField('image_path', '');
    }

    //生成XML文件
    public function xmlText() {
        $perPage        = 10;
        $totalRows      = $this->getCountRecords();
        $totalPage      = ceil($totalRows / $perPage);
        $whereType      = $this->genWhereModelType();
        $this->_totalRecord     = 0;
        for($page = 0; $page < $totalPage; $page ++) {
            $recordList         = $this->getXmlRecordList($whereType, $page, $perpage);
            $this->genXmlContent($recordList);
        }

        $this->writeSubMenuXmlFile();

        return true;
    }

    //得到XML的数据集
    protected function getXmlRecordList($whereStr, $page, $perpage = 10) {
        return $this->field(self::$xmlFields)->where($whereStr)->order(self::$orderFields)->page($page, $perpage)->select();
    }

    //写入XML
    protected function writeXml($xmlContent) {
        $xmlContent     = sprintf(self::$rootNode, $xmlContent);
        $xml            = new Xml($this->_xmlFilePath, $xmlContent);
        
        return  $xml->save();
    }

    //生成主页的XML内容
    protected function genXmlContent($recordList) {
        if(empty($recordList)) {
            return '';
        }
        foreach($recordList as $record) {
            $this->_totalRecord ++;
            if(!empty($record['image_path'])) {
                $record['image_path']   = $this->_uploadDir . '/' . $record['image_path'];
            }
            $this->_xmlFilePath = sprintf(self::$xmlFilePath, $this->_modelTypeId, $this->_totalRecord);
            $xmlContent         = vsprintf(self::$childNode, $record);
            $this->genSubXmlContent($record['text_name']);
            if(false === $this->writeXml($xmlContent)) {
                Logger::log('写入XML内容失败！' . __CLASS__);
            }
        }

        return $xmlContent;
    }

    //写入二级子菜单文件
    protected function writeSubMenuXmlFile() {
        $this->_xmlFilePath = sprintf(self::$subXmlFilePath, $this->_modelTypeId);
        $xmlContent         = sprintf(self::$subRootNode, $this->_subXmlContent);
        $xml                = new Xml($this->_xmlFilePath, $xmlContent);
        
        return  $xml->save();
    }

    //生成二级菜单
    protected function genSubXmlContent($textTitle) {
        $this->_subXmlContent   .= sprintf(self::$subChildNode, $textTitle, $this->_xmlFilePath);
    }

    //生成WhereIn条件语句
    protected function genWhereIn($field, array $values) {
        return '`' . $field . '` IN (' . implode(',', $values) . ', -1)';
    }

    //上传文件方法
    protected function uploadFile() {
        if(!empty($_FILES['image_path']['name'])) {
            $uploadFile     = new UploadFile($_FILES['image_path'],
                                        $this->_uploadDir,
                                        $this->_imageTypes,
                                        $this->_imageSize);
            if(false === $uploadFile->upload()) {
                $this->_error->setErrorInfo($uploadFile->getError());
                return false;
            }
            $arrPath    = explode('/', $uploadFile->getUploadFilePath());
            $_POST['image_path']    = array_pop($arrPath);
            $_POST['image_path']    = array_pop($arrPath) . '/' . $_POST['image_path'];
            //生成缩略图
            $this->genThumbImage($uploadFile->getUploadFilePath());
            
            return true;
        }

        return true;
    }

    //生成缩略图
    protected function genThumbImage($srcFilePath) {
        $thumbImgName  = $this->genThumbImageName($srcFilePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            $genResult      = Image::thumb($srcFilePath, $thumbImgPath, $thumbInfo['t'], $thumbInfo['w'], $thumbInfo['h'], $thumbInfo['i']);
            if(!$genResult) {
               //log 
            }
        } 
    }

    //得到缩略图的路径及文件名
    public function genThumbImageName($srcFilePath) {
        return mb_substr($srcFilePath , 0, strrpos($srcFilePath, '.'), 'utf-8');
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(!empty($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath, $this->_uploadDir);
        }

        return true;
    }

    //删除相关缩略图
    protected function delThumbImageFile($filePath) {
        $thumbImgName  = $this->genThumbImageName($filePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            LittleTools::deleteFile($thumbImgPath, $this->_uploadDir);
        } 
    }

    public function getUploadDir() {
        return preg_replace('/public\//i', '', $this->_uploadDir);
    }

    //得到模块的类型ID
    public function getModelTypeId() {
        if(empty($this->_modelTypeId)) {
            return $_GET['type'];
        }

        return $this->_modelTypeId;
    }

}

?>
